package com.vcredit.creditcat.handler;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.util.UrlUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by wichell on 2017/11/14.
 */
public class CreditCatRedirectStrategy implements RedirectStrategy {
    protected final Log logger = LogFactory.getLog(getClass());

    private boolean contextRelative;

    @Override
    public void sendRedirect(HttpServletRequest request, HttpServletResponse response, String url) throws IOException {
        String redirectUrl = calculateRedirectUrl(request.getContextPath(), url,request.getRequestURL().toString());
        System.out.println("getRequestURI:"+request.getRequestURL().toString());
        System.out.println("getRemoteAddr:"+request.getRemoteAddr());
        System.out.println("getRemoteHost:"+request.getRemoteHost());
        System.out.println("getContextPath:"+request.getContextPath());
        redirectUrl = response.encodeRedirectURL(redirectUrl);

        if (logger.isDebugEnabled()) {
            logger.debug("Redirecting to '" + redirectUrl + "'");
        }

        response.sendRedirect(redirectUrl);
    }

    private String calculateRedirectUrl(String contextPath, String url,String requestURL) {

        if (!UrlUtils.isAbsoluteUrl(url)) {
            if (contextRelative) {
                return url;
            } else {

                if(requestURL.contains("loan.vcredit.com")
                        ||requestURL.contains("api.creditcat.cn")) {
                    contextPath = contextPath.replace("creditcat-admin", "admin");
                }

                return contextPath + url;
            }
        }


        // Full URL, including http(s)://

        if (!contextRelative) {
            return url;
        }

        // Calculate the relative URL from the fully qualified URL, minus the scheme and base context.
        url = url.substring(url.indexOf("://") + 3); // strip off scheme
        url = url.substring(url.indexOf(contextPath) + contextPath.length());

        if (url.length() > 1 && url.charAt(0) == '/') {
            url = url.substring(1);
        }

        return url;
    }

    /**
     * If <tt>true</tt>, causes any redirection URLs to be calculated minus the protocol
     * and context path (defaults to <tt>false</tt>).
     */
    public void setContextRelative(boolean useRelativeContext) {
        this.contextRelative = useRelativeContext;
    }

}
